<template>
    <Header :key="refreshKey"></Header>

    <!-- 主内容区域 -->
    <main class="container max-w-screen-lg mx-auto p-6 md:mx-auto">
        <!-- grid 表格布局，分为 4 列 -->
        <div class="grid grid-cols-6">
            <!-- 左边栏，占用 3 列 -->
            <div class="col-span-6 md:col-span-4 mb-3">
                <!-- 轮播图 用element-->
                <el-carousel class="relative h-56 md:h-80" :interval="4000" arrow="always">
                    <el-carousel-item v-for="(item, index) in topArticleList" :key="index">
                        <router-link class="hand-style" :to="'/article/' + item.id">
                            <img class="w-full" v-lazy="item.cover" :key="index" />
                            <h3 class="absolute h-10 w-full text-2xl text-center bottom-8 text-white font-medium bg-black bg-opacity-30">{{ item.title }}</h3>
                        </router-link>
                    </el-carousel-item>
                </el-carousel>

                <!-- 文章列表，grid 表格布局，分为 1 列 -->
                <div class="grid grid-cols-1 gap-4">
                    <!-- 标签导航 -->
                    <TabNav ref="tabNavRef" @handleAcitve="handleArticlePage"></TabNav>
                    <!-- 具体文章列表 -->
                    <div v-if="articles !== null">
                        <div v-for="(article, index) in articles" :key="index"
                            class="hover:scale-[1.02] mb-4 col-span-1 md:col-span-1 md:h-48 ">
                            <div class="relative bg-white h-full border border-gray-200 rounded-lg dark:bg-gray-800 dark:border-gray-700"
                                style="box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);">
                                <!-- 文章封面 -->
                                <!-- <a @click="goArticleDetailPage(article.id)" class="hand-style">
                                    <img v-if="article.cover"  :src="article.cover" />
                                    <img v-else src="@/assets/noPicture.png">
                                </a> -->
                                <a @click="goArticleDetailPage(article.id)"
                                    class="hover:scale-[1.03] hand-style h-10 w-10 overflow-hidden border-x-2 border-y-2 rounded-lg md:absolute md:right-5 md:top-5 md:w-48 md:h-32">
                                    <img v-if="article.cover" v-lazy="article.cover" class="object-cover" />
                                    <img v-else src="@/assets/noPicture.png">
                                </a>
                                <!-- 是否置顶 -->
                                <div v-if="article.isTop"
                                    class="absolute inline-flex items-center justify-center w-14 h-7 text-xs font-bold text-white bg-red-500 border-2 border-white rounded-full -top-2 -end-2 dark:border-gray-900">
                                    置顶
                                </div>
                                <div class="p-5 h-full">

                                    <!-- 文章标题 -->
                                    <a @click="goArticleDetailPage(article.id)">
                                        <h2
                                            class="xiahuaxian hand-style w-fit mb-2 text-2xl font-bold tracking-tight text-gray-900 dark:text-white">
                                            {{ article.title }}</h2>
                                    </a>
                                    <!-- 文章摘要 -->
                                    <p v-if="article.summary"
                                        class="mb-3 h-20 font-normal text-gray-500 dark:text-gray-400 md:w-2/3">
                                        {{ article.summary.length > 50 ? article.summary.substring(0, 70) + '...' :
                    article.summary }}
                                    </p>
                                    <!-- 文章发布时间、所属标签 -->
                                    <p class="flex items-center font-normal text-gray-400 text-sm dark:text-gray-400">
                                        <!-- 发布时间 -->
                                        <svg class="inline w-3 h-3 mr-2 text-gray-400"
                                            aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none"
                                            viewBox="0 0 20 20">
                                            <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"
                                                stroke-width="2"
                                                d="M5 1v3m5-3v3m5-3v3M1 7h18M5 11h10M2 3h16a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1Z" />
                                        </svg>
                                        {{ article.createDate }}

                                        <!-- 标签 -->
                                        <div class="ml-2">
                                            <span v-for="(tag, tagIndex) in article.tags" :key="tagIndex"
                                                @click="goTagArticleListPage(tag.id, tag.name)"
                                                :style="getBgColor()"
                                                class="tag hand-style text-xs text-white font-medium px-2.5 py-0.5 rounded hover:bg-black">
                                                {{ tag.name }}
                                            </span>
                                        </div>
                                        <!-- 浏览量 -->
                                        <div class="flex">
                                            <svg-icon class="small mr-1 ml-2" iconName="icon-yueduliang"></svg-icon>
                                            <span class=" text-xs ">阅读 {{ article.readNum }}</span>
                                        </div>
                                        <!-- 评论量 -->
                                        <div class="flex">
                                            <svg-icon class="small mr-1 ml-2" iconName="icon-pinglun"></svg-icon>
                                            <span class=" text-xs">评论 {{ article.commentNum }}</span>
                                        </div>
                                    </p>
                                </div>
                            </div>
                        </div>
                        <!-- 分页按钮 -->
                        <div>
                            <ym-page :pageNo="current" :pages="pages" @changePage="moreArticle" />
                        </div>
                    </div>

                    <div v-else class="flex justify-center">
                        <ym-empty message="暂无文章" />
                    </div>

                </div>
                <!-- 分页 -->

                <!-- <nav aria-label="Page navigation example" class="mt-10 flex justify-center" v-if="pages > 1">
                    <ul class="flex items-center -space-x-px h-10 text-base"> -->
                <!-- 上一页 -->
                <!-- <li>
                            <a @click="getArticles(current - 1)"
                                class="flex items-center justify-center px-4 h-10 ml-0 leading-tight text-gray-500 bg-white border border-gray-300 rounded-l-lg hover:bg-gray-100 hover:text-gray-700 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white"
                                :class="[current > 1 ? '' : 'cursor-not-allowed']">

                                <span class="sr-only">上一页</span>
                                <svg class="w-3 h-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none"
                                    viewBox="0 0 6 10">
                                    <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"
                                        stroke-width="2" d="M5 1 1 5l4 4" />
                                </svg>
                            </a>
                        </li> -->
                <!-- 页码 -->
                <!-- <li v-for="(pageNo, index) in pages" :key="index">
                            <a @click="getArticles(pageNo)"
                                class="flex items-center justify-center px-4 h-10 leading-tight border  dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white"
                                :class="[pageNo == current ? 'text-blue-600  bg-blue-50 border-blue-300 hover:bg-blue-100 hover:text-blue-700' : 'text-gray-500 border-gray-300 bg-white hover:bg-gray-100 hover:text-gray-700']">
                                {{ index + 1 }}
                            </a>
                        </li> -->
                <!-- 下一页 -->
                <!-- <li>
                            <a @click="getArticles(current + 1)"
                                class="flex items-center justify-center px-4 h-10 leading-tight text-gray-500 bg-white border border-gray-300 rounded-r-lg hover:bg-gray-100 hover:text-gray-700 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white"
                                :class="[current < pages ? '' : 'cursor-not-allowed']">
                                <span class="sr-only">下一页</span>
                                <svg class="w-3 h-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none"
                                    viewBox="0 0 6 10">
                                    <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"
                                        stroke-width="2" d="m1 9 4-4-4-4" />
                                </svg>
                            </a>
                        </li> -->
                <!-- </ul>
                </nav> -->
            </div>


            <!-- 右边侧边栏，占用一列 -->
            <aside class="col-span-6 md:col-span-2">
                <div class="top-[5.5rem] md:pl-7">
                    <!-- 博主信息 -->
                    <UserInfoCard></UserInfoCard>

                    <!-- 分类 -->
                    <CategoryListCard></CategoryListCard>

                    <!-- 标签 -->
                    <TagListCard></TagListCard>

                    <!-- 天气 -->
                    <WeatherCard></WeatherCard>
                </div>

            </aside>
        </div>

    </main>

    <Footer></Footer>
</template>

<script setup>
import Header from '@/layouts/frontend/components/Header.vue'
import Footer from '@/layouts/frontend/components/Footer.vue'
import UserInfoCard from '@/layouts/frontend/components/UserInfoCard.vue'
import CategoryListCard from '@/layouts/frontend/components/CategoryListCard.vue'
import TagListCard from '@/layouts/frontend/components/TagListCard.vue'
import WeatherCard from '@/layouts/frontend/components/WeatherCard.vue'
import TabNav from '@/layouts/frontend/components/TabNav.vue'
import { initTooltips } from 'flowbite'
import { onMounted, onUnmounted, ref } from 'vue'
import { getArticlePageList } from '@/api/frontend/article'
import { getCategoryArticlePageList } from '@/api/frontend/category'
import { useRouter } from 'vue-router'

const router = useRouter()

const refreshKey = ref(0)

const timer = setTimeout(() => {
    refreshKey.value += 1
}, 500)

onUnmounted(() => {
    clearTimeout(timer)
})

// initialize components based on data attribute selectors
onMounted(() => {
    initTooltips();
})

// 文章集合
const articles = ref([])
// 当前页码
const current = ref(1)
// 每页显示的文章数
const size = ref(3)
// 总文章数
const total = ref(0)
// 总共多少页
const pages = ref(0)


function getArticles(currentNo) {
    // 上下页是否能点击判断，当要跳转上一页且页码小于 1 时，则不允许跳转；当要跳转下一页且页码大于总页数时，则不允许跳转
    // if (currentNo < 1 || (pages.value > 0 && currentNo > pages.value)) return

    // 调用分页接口渲染数据  status 0 后端定义0 默认为获取最新
    getArticlePageList({ current: currentNo, size: size.value, status: 0 }).then((res) => {
        if (res.success) {
            articles.value = res.data
            current.value = res.current
            size.value = res.size
            total.value = res.total
            pages.value = res.pages

            // 数据更新后再进行置顶文章筛选
            filterTopArticle();
        }
    })
}
// 进入页面获取文章列表初始化
getArticles(current.value)


// // 去分类-文章列表
// const goCategoryArticleListPage = (id, name) => {
//     // 跳转时通过 query 携带参数（分类 ID、分类名称）
//     router.push({ path: '/category/article/list', query: { id, name } })
// }

// 去标签-文章列表
const goTagArticleListPage = (id, name) => {
    // 跳转时通过 query 携带参数（标签 ID、标签名称）
    router.push({ path: '/tag/article/list', query: { id, name } })
}

// 去文章详情
const goArticleDetailPage = (articleId) => {
    // 跳转时路径带上文章id
    router.push('/article/' + articleId)
}

// 加载更多文章 （还需判断当前在那个tab下）
const moreArticle = async () => {
    // 当前页码加1
    current.value = current.value + 1
    // 判断当前tab的分类id，其实也就是index
    let id = tabNavRef.value.ActiveCategoryId ? tabNavRef.value.ActiveCategoryId : 0
    let res = null
    if (id == 0 || id == 1) {
        // 每次点击最新或最热
        res = await getArticlePageList({ current: current.value, size: size.value, status: id })
    } else {
        // 点的是具体的分类
        res = await getCategoryArticlePageList({
            current: current.value,
            size: size.value,
            id: id
        })
    }
    if (res.success) {
        articles.value.push(...res.data)
    }
}

// 绑定Tab导航栏引用
const tabNavRef = ref(0)

// Tab导航栏获取文章
const handleArticlePage = async () => {
    // 如果点击的是最新和最热 这里的id其实就是tab的index
    let id = tabNavRef.value.ActiveCategoryId
    let res = null
    if (id == 0 || id == 1) {
        // 每次点击最新或最热 当前页要重新设置为1
        current.value = 1
        res = await getArticlePageList({ current: current.value, size: size.value, status: id })
    } else {
        // 每次切换tab类型 当前页要重新设置为1
        current.value = 1
        // 点的是具体的分类
        res = await getCategoryArticlePageList({
            current: current.value,
            size: size.value,
            id: id
        })
    }
    console.log(res)
    if (res.success) {
        articles.value = res.data
        current.value = res.current
        size.value = res.size
        total.value = res.total
        pages.value = res.pages
    }
}

// ===============处理轮播图=========================

// 定义置顶的文章
const topArticleList = ref([])

// 筛选置顶的文章
const filterTopArticle = () => {
    topArticleList.value = articles.value.filter(item => item.isTop);
}


// ================处理首页文章的标签的颜色====================

// 随机颜色数组
// const colorList = [
//   '#f68a90',
//   '#9fe286',
//   '#ffc07e',
//   '#b3adea',
//   '#6fc1ff',
//   '#83d4bf',
//   '#dabb9c',
//   '#aec7de',
//   '#ff936b'
// ]

const colorList = [
    'linear-gradient(to right, #FFF886 0%, #F072B6 100%)',
    'linear-gradient(to right, #EE9CA7 0%, #FFDDE1 100%)',
    'linear-gradient(to right, #4CA1AF 0%, #C4E0E5 100%)',
    'linear-gradient(to right, #FF626E 0%, #FFBE71 100%)',
    'linear-gradient(to right, #BB5571 0%, #F0C6B5 100%)',
    'linear-gradient(to right, #BC95C6 0%, #7DC4CC 100%)',
    'linear-gradient(to right, #6190E8 0%, #A7BFE8 100%)',
    'linear-gradient(to right, #4DA2CB 0%, #67B26F 100%)',
    'linear-gradient(to right, #0DCDA4 0%, #C2FCD4 100%)',
    'linear-gradient(to right, #06BEB6 0%, #028EA1 100%)',
    'linear-gradient(to right, #67F9D4 0%, #FF9554 100%)',
    'linear-gradient(to right, #F9957E 0%, #F3F5D0 100%)',
    'linear-gradient(to right, #FF9A9E 0%, #F6E745 100%)',
    'linear-gradient(to right, #18545A 0%, #F1F2B5 100%)',
    'linear-gradient(to right, #D39340 0%, #FFD194 100%)',
    'linear-gradient(to right, #9600FF 0%, #E1E1E1 100%)',
]

const getBgColor = () => {
  let n = Math.floor(Math.random() * 15)
  return { 
    background: colorList[n]  
  }
}


</script>
<style scoped>
.object-cover {
    object-fit: cover;
    width: 100%;
    height: 100%;
}
.tag:hover {
    border-radius: 0;
    background: #000 !important;
}

/* 文章标题下划线 */
.xiahuaxian {
    background: linear-gradient(to right, #FFF886, #F072B6) no-repeat right bottom;
    background-size: 0px 2px;
    transition: background-size .35s;
}
.xiahuaxian:hover {
    background-size: 100% 2px;
    background-position: left bottom;
}
</style>